package com.xgkj.diyiketang.activity;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.data.SellerInfo;
import com.xgkj.diyiketang.task.SendFlowerTask;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.data.CommentAdapter;
import com.xgkj.diyiketang.activity.data.DetailFansAdapter;
import com.xgkj.diyiketang.data.CommentInfo;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.data.VideoInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.AddOrCancleFocusTask;
import com.xgkj.diyiketang.task.CommentListTask;
import com.xgkj.diyiketang.task.FansListTask;
import com.xgkj.diyiketang.task.GetUserInfoTask;
import com.xgkj.diyiketang.task.PublishCommentTask;
import com.xgkj.diyiketang.task.ShouCangTask;
import com.xgkj.diyiketang.task.TouPiaoTask;
import com.xgkj.diyiketang.task.VideoDetailTask;
import com.xgkj.diyiketang.task.ZanOrCaiTask;
import com.xgkj.diyiketang.util.AccessTokenKeeper;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.util.WeixinShareUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;
import com.xgkj.diyiketang.weidget.MyCustomListView;
import com.xgkj.diyiketang.weidget.MyScrollView;
import com.xgkj.diyiketang.wxapi.WXEntryActivity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * Created by Administrater on 2015/12/18.
 */
public class VideoDetailActivity extends BaseActivity implements View.OnClickListener, IWeiboHandler.Response {
    protected Context mContent;
    private VideoInfo info;
    private GridView fansGrid;
    private Button pinglunBtn;
    private ClearableEditText cmtContant;
    private DetailFansAdapter dtfansAdapter;
    private MyCustomListView commentList;
    private CommentAdapter cmtAdapter;
    private TextView shang;
    private TextView zan;
    private TextView bofangliang;
    private TextView shoucang;
    private TextView fenxiang;
    //private TextView cai;
    private ImageView userLogo;
    private TextView nickText;
    private TextView signText;
    private Button focusImge;
    private TextView videoInstrText;
    private TextView videoCreatedateText;
    private MyScrollView mySroll;
    //private VideoInfo info;
//    private YoukuBasePlayerManager basePlayerManager;
    // 播放器控件
//    private YoukuPlayerView mYoukuPlayerView;

    // 需要播放的视频id
    private String youkuvid;
    private String userid;
    private String vdid;
    // YoukuPlayer实例，进行视频播放控制
//    private YoukuPlayer youkuPlayer;
    private int videoDetailTaskId = -1;
    private int zanTaskId = -1;
    private int caiTaskId = -1;
    private int cancleCaiId = -1;
    private int getUserInfoTaskId = -1;
    private int fanListTaskId = -1;
    private int commentListTaskId = -1;
    private int publishCmtTaskId = -1;
    private int addFocusTaskId = -1;
    private int shoucangTaskId = -1;
    private String zanNum;
    //private String caiNum;
    private String shangNum;
    private String shoucangNum;
    private String fenxiangNum;
    private boolean isZan;
    private boolean isCollect;
    //private boolean isCai;
    private String cmtText;
    private String mSign;
    private String bofangNum;
    private int currentPage = 1;
    private ImageView back;
    private Button moreFans;
    EatShowUserInfo userinfo;
    private ImageView addFocusImg;
    private PopupWindow popWindow;

    private WeixinShareReceive mWeixinShareReceive;
    private String weixinsharetype;
    private String weixinuseropenid;
    private String weibouserid;
    private Bitmap weiboShareBitmap;
    private byte[] weixinshareByte;
    private IWXAPI api;
    private IWeiboShareAPI mWeiboShareAPI = null;
    private String shoucangtype;
    public static Tencent mTencent;
    private LinearLayout mFansLayout;
    private TextView mToupiao;
    private String toupiaoNum;
    private int tpTaskId = -1;

    private String share_title;
    private boolean isCanSai;
    private int cancleFocusTaskId = -1;
    private int shareNumTaskId = -1;

    private SellerInfo businessInfo;
    private ImageView sellerlogo;
    private TextView sellerName;
    private TextView sellerType;
    private TextView sellerRenjun;
    private RatingBar rating;
    private RelativeLayout sellerLayout;
    private ImageView fansListDivider;

    private String teacherString;
    private String feeString;
    private String titleString;

    private String songhuaNum;
    private boolean isFirst;
    private int sendflourTaskId = -1;
    private WebView mWebView;
    protected static final FrameLayout.LayoutParams FULL_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;
    private String play_url;
    private Handler mHandler = new Handler();
    private int width, height;
    private LinearLayout webLayout;
    private int webwidth, webheight;
    private TextView videoScoreText;

    private VideoView mVideoView;
    private String isUse;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.video_detail);
        mContent = this;
        width = ViewUtil.getScreenWidth(mContext);
        height = ViewUtil.getScreenHeight(mContext);
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, this.getApplicationContext());  //1104548348
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);
//        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this,
//                ProtocolConst.WEIBO_APP_KEY);//这粒要换
//        mWeiboShareAPI.registerApp();
//        if (savedInstanceState != null) {
//            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
//        }
        getData();
        initView();
        /*basePlayerManager = new YoukuBasePlayerManager(this) {

            @Override
            public void setPadHorizontalLayout() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onInitializationSuccess(YoukuPlayer player) {
                // TODO Auto-generated method stub
                // 初始化成功后需要添加该行代码
                addPlugins();

                // 实例化YoukuPlayer实例
                youkuPlayer = player;

                // 进行播放
//                goPlay();
            }

            @Override
            public void onSmallscreenListener() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onFullscreenListener() {
                // TODO Auto-generated method stub

            }
        };
        basePlayerManager.onCreate();
        */

//        // 通过上个页面传递过来的Intent获取播放参数
//        getIntentData(getIntent());
//
//        if (TextUtils.isEmpty(id)) {
//            vid = "XODQwMTY4NDg0"; // 默认视频
//        } else {
//            vid = id;
//        }

//        Intent intent = getIntent();
//        vdid = intent.getStringExtra("videoid");
//        //info = (VideoInfo) intent.getSerializableExtra("INFO");
//        userid = intent.getStringExtra("UID");
//        youkuvid = intent.getStringExtra("YOUKUVIDEOID");
        // 播放器控件
//        mYoukuPlayerView = (YoukuPlayerView) this
//                .findViewById(R.id.full_holder);
        //控制竖屏和全屏时候的布局参数。这两句必填。
//        mYoukuPlayerView
//                .setSmallScreenLayoutParams(new LinearLayout.LayoutParams(
//                        LinearLayout.LayoutParams.MATCH_PARENT,
//                        LinearLayout.LayoutParams.WRAP_CONTENT));
//        mYoukuPlayerView
//                .setFullScreenLayoutParams(new LinearLayout.LayoutParams(
//                        LinearLayout.LayoutParams.MATCH_PARENT,
//                        LinearLayout.LayoutParams.MATCH_PARENT));
        // 初始化播放器相关数据
//        mYoukuPlayerView.initialize(basePlayerManager);




    }

    private void getData() {
        Intent intent = getIntent();
        vdid = intent.getStringExtra("videoid");
        //info = (VideoInfo) intent.getSerializableExtra("INFO");
        userid = intent.getStringExtra("UID");
        isUse = intent.getStringExtra("isUse");
        youkuvid = intent.getStringExtra("YOUKUVIDEOID");
        titleString = intent.getStringExtra("TITLE");
        feeString = intent.getStringExtra("FEE");
        teacherString = intent.getStringExtra("ZUOZHE");
        if (!ViewUtil.isNull(youkuvid)) {
//            play_url = "http://qiniu.sjmingze.com/%E9%83%91%E9%92%A7%E6%82%9F%E5%85%84.mp4";
            play_url = "http://app.sjmingze.com/yzb/yk.html?vid=" + youkuvid;
        }
        getUserInfo();
    }


    @Override
    public void onBackPressed() { // android系统调用
//        Logger.d("sgh", "onBackPressed before super");
//        super.onBackPressed();
//        Logger.d("sgh", "onBackPressed");
//        basePlayerManager.onBackPressed();

        if (customView != null) {
            hideCustomView();
            return;
        }

        if (isFull) {
            mWebView.loadUrl("javascript:window.local_js.fullScreen();var youku=document.getElementById('youkuplayer');youku.style.width='" + webwidth + "px';youku.style.height='" + webwidth * 9 / 16 + "px';isFull = false;");
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
//        super.onConfigurationChanged(newConfig);
//        basePlayerManager.onConfigurationChanged(newConfig);

        if (newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            hideCustomView();
        }
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        basePlayerManager.onDestroy();
        if (mWebView != null) {
            mWebView.destroy();
        }
        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        boolean managerKeyDown = basePlayerManager.onKeyDown(keyCode, event);
//        if (basePlayerManager.shouldCallSuperKeyDown()) {
//            return super.onKeyDown(keyCode, event);
//        } else {
//            return managerKeyDown;
//        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    public void onLowMemory() { // android系统调用
        super.onLowMemory();
//        basePlayerManager.onLowMemory();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        basePlayerManager.onPause();
        if (mWebView != null) {
            mWebView.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        basePlayerManager.onResume();
        if (mWebView != null) {
            mWebView.onResume();
        }
        currentPage = 1;
        getCommentList();
//        getUserInfo();
    }

    @Override
    public boolean onSearchRequested() { // android系统调用
//        return basePlayerManager.onSearchRequested();
        return super.onSearchRequested();
    }

    @Override
    protected void onStart() {
        super.onStart();
//        basePlayerManager.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
//        basePlayerManager.onStop();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
//        mWeiboShareAPI.handleWeiboResponse(intent, this);
        setIntent(intent);
        getData();
        // 通过Intent获取播放需要的相关参数
        //  getIntentData(intent);

        // 进行播放
        goPlay();
    }

    private void goPlay() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo currentNet = cm.getActiveNetworkInfo();
        if (currentNet == null) {
            Toast.makeText(mContext, R.string.no_network,
                    Toast.LENGTH_SHORT).show();
        } else if (currentNet.getType() == ConnectivityManager.TYPE_MOBILE) {
            showshujuDialog();
        } else {
//            youkuPlayer.playVideoWithPassword(youkuvid, "123456");
            if (!ViewUtil.isNull(youkuvid)) {
                play_url = "http://app.sjmingze.com/yzb/yk.html?vid=" + youkuvid;
//                play_url = "http://qiniu.sjmingze.com/%E9%83%91%E9%92%A7%E6%82%9F%E5%85%84.mp4";
                mWebView.loadUrl(play_url);
            }
        }
    }


    /**
     * 视频播放全屏
     **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FrameLayout(mContext);
        fullscreenContainer.addView(view, FULL_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, FULL_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /**
     * 隐藏视频全屏
     */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        mWebView.setVisibility(View.VISIBLE);
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (visible) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }


    private void initView() {
        webLayout = (LinearLayout) findViewById(R.id.web_layout);
//        mVideoView = (VideoView) findViewById(R.id.video_view);
        webLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                int width = ViewUtil.getScreenWidth(mContext);
                int height = width * 9 / 16;
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
                webLayout.setLayoutParams(params);
            }
        }, 500);

        mWebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true); // 关键点
        webSettings.setAllowFileAccess(true); // 允许访问文件
        webSettings.setSupportZoom(true); // 支持缩放
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 不加载缓存内容
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
//                return super.shouldOverrideUrlLoading(view, url);
            }

            @TargetApi(21)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (Build.VERSION.SDK_INT >= 21) {
                    view.loadUrl(request.getUrl().toString());
                }
                return true;
//                return super.shouldOverrideUrlLoading(view, request);
            }

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString().toLowerCase();
                if (!hasAd(mContext, url)) {
                    return super.shouldInterceptRequest(view, request);//正常加载
                } else {
                    return new WebResourceResponse(null, null, null);//含有广告资源屏蔽请求
                }
            }


            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                String url_s = url.toLowerCase();
                if (!hasAd(mContext, url_s)) {
                    return super.shouldInterceptRequest(view, url);//正常加载
                } else {
                    return new WebResourceResponse(null, null, null);//含有广告资源屏蔽请求
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String tag = getTagByUrl(url);
                float scale = view.getScale();
                System.out.println(scale);
                webwidth = (int) (width / scale);
                webheight = (int) (height / scale);
//                view.loadUrl("javascript:console.log(document.getElementsByTagName('html')[0].innerHTML)");
//                view.loadUrl("javascript:document.getElementsByClassName('" + tag + "')[0].addEventListener('click',function(){window.local_js.fullScreen();return false;});");
                view.loadUrl("javascript:var isFull = false;document.getElementsByClassName('" + tag + "')[0].addEventListener('click',function(){window.local_js.fullScreen();console.log('width:" + webwidth + ",height:" + webheight + "'); var youku = document.getElementById('youkuplayer'); if(!isFull){youku.style.width='" + webheight + "px';youku.style.height='" + webwidth + "px'; isFull = true;}else{youku.style.width='" + webwidth + "px';youku.style.height='" + webwidth * 9 / 16 + "px';isFull = false;}return false;});");
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.addJavascriptInterface(new JsObject(), "local_js");

        //改为注入js实现
        /*
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public View getVideoLoadingProgressView() {
                FrameLayout frameLayout = new FrameLayout(mContext);
                frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                return frameLayout;
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
//                super.onShowCustomView(view, callback);
                showCustomView(view,callback);
            }

            @Override
            public void onHideCustomView() {
//                super.onHideCustomView();
                hideCustomView();
            }
        });*/

        mWebView.postDelayed(new Runnable() {
            @Override
            public void run() {
                int width = ViewUtil.getScreenWidth(mContext);
                int height = width * 9 / 16;
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
                mWebView.setLayoutParams(params);
                if (!ViewUtil.isNull(play_url)) {
                    mWebView.loadUrl(play_url);
                }
            }
        }, 500);


        mySroll = (MyScrollView) findViewById(R.id.detail_scroll);
        mySroll.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll() {
                getCommentList();
            }
        });
        shang = (TextView) findViewById(R.id.shang);
        zan = (TextView) findViewById(R.id.zan);
        bofangliang = (TextView) findViewById(R.id.bofangliang);
        bofangliang.setOnClickListener(this);
        shoucang = (TextView) findViewById(R.id.detail_shoucang);
        fenxiang = (TextView) findViewById(R.id.fenxiang);
        //cai = (TextView) findViewById(R.id.cai);
        mToupiao = (TextView) findViewById(R.id.toupiao);
        userLogo = (ImageView) findViewById(R.id.user_head_image);
        userLogo.setOnClickListener(this);
        mFansLayout = (LinearLayout) findViewById(R.id.fanslist_layout);
        fansListDivider = (ImageView) findViewById(R.id.fanslist_divider);
        nickText = (TextView) findViewById(R.id.user_name);
        signText = (TextView) findViewById(R.id.user_sign);
        focusImge = (Button) findViewById(R.id.user_focus);
        addFocusImg = (ImageView) findViewById(R.id.addfocus);
        videoInstrText = (TextView) findViewById(R.id.video_instruction);
        videoCreatedateText = (TextView) findViewById(R.id.video_createDate);
        videoScoreText = (TextView) findViewById(R.id.pingfen);
        fansGrid = (GridView) findViewById(R.id.fans_list);
        dtfansAdapter = new DetailFansAdapter(mContext);
        fansGrid.setAdapter(dtfansAdapter);
        commentList = (MyCustomListView) findViewById(R.id.comment_list);
        cmtAdapter = new CommentAdapter(mContext, vdid, 1);
        commentList.setAdapter(cmtAdapter);
        pinglunBtn = (Button) findViewById(R.id.fabiaopinglun);
        pinglunBtn.setOnClickListener(this);
        cmtContant = (ClearableEditText) findViewById(R.id.pinglun);
        back = (ImageView) findViewById(R.id.back);
        moreFans = (Button) findViewById(R.id.more_fans_list);
        moreFans.setOnClickListener(this);
        back.setOnClickListener(this);
        shang.setOnClickListener(this);
        zan.setOnClickListener(this);
        //cai.setOnClickListener(this);
        userLogo.setOnClickListener(this);
        focusImge.setOnClickListener(this);
        addFocusImg.setOnClickListener(this);
        fenxiang.setOnClickListener(this);
        shoucang.setOnClickListener(this);
        mToupiao.setOnClickListener(this);
        sellerlogo = (ImageView) findViewById(R.id.sellerlogo);
        sellerName = (TextView) findViewById(R.id.sellername);
        sellerType = (TextView) findViewById(R.id.sellertype);
        sellerRenjun = (TextView) findViewById(R.id.sellrenjun);
        rating = (RatingBar) findViewById(R.id.ratingbar_Small);
        sellerLayout = (RelativeLayout) findViewById(R.id.seller_layout);
        initPopWindow();
        //getVideoDetail();
//        getUserInfo();


    }

    public static boolean hasAd(Context context, String url) {
        Resources res = context.getResources();
        String[] adUrls = res.getStringArray(R.array.adBlockUrl);
        for (String adUrl : adUrls) {
            if (url.contains(adUrl)) {
                return true;
            }
        }
        return false;
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_pop,
                null);
        ((ImageView) view.findViewById(R.id.share_to_timeline))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weixinfriend))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weibo))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_qq))
                .setOnClickListener(this);
        popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    private void addShareNum() {
        ZanOrCaiTask shareTask = new ZanOrCaiTask(vdid, "1");
        shareTask.addListener(new VideoDetailTaskListener(mContext));
        shareNumTaskId = getEatShowApp().getTaskManager().addTask(shareTask);
    }

    private void getAnchorFansList() {
        FansListTask fansTask = new FansListTask(5, 1, userid);
        fansTask.addListener(new VideoDetailTaskListener(mContext));
        fanListTaskId = getEatShowApp().getTaskManager().addTask(fansTask);
    }

    private void getUserInfo() {
        GetUserInfoTask uTask = new GetUserInfoTask(userid);
        uTask.addListener(new VideoDetailTaskListener(mContext));
        getUserInfoTaskId = getEatShowApp().getTaskManager().addTask(uTask);
    }

    private void getVideoDetail() {
        VideoDetailTask vdTask = new VideoDetailTask(vdid);
        vdTask.addListener(new VideoDetailTaskListener(mContent));
        videoDetailTaskId = getEatShowApp().getTaskManager().addTask(vdTask);
    }

    private void getCommentList() {
        if (currentPage == 0) {
            commentList.setNoNextPage();
            return;
        }
        CommentListTask cmtListTask = new CommentListTask(10, currentPage, vdid);
        cmtListTask.addListener(new VideoDetailTaskListener(mContext));
        commentListTaskId = getEatShowApp().getTaskManager().addTask(cmtListTask);

    }

    private void publishComment() {
        //cmtText = cmtContant.getText().toString().trim();
        PublishCommentTask pcTask = new PublishCommentTask(vdid, cmtText, "", "");
        pcTask.addListener(new VideoDetailTaskListener(mContext));
        publishCmtTaskId = getEatShowApp().getTaskManager().addTask(pcTask);
    }

    private void doSendFlour() {
        SendFlowerTask sTask = new SendFlowerTask(1, userid, vdid);
        sTask.addListener(new VideoDetailTaskListener(mContext));
        sendflourTaskId = getEatShowApp().getTaskManager().addTask(sTask);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_head_image:
//                startActivity(AnchorActivity.getIntent(mContext, userinfo.getUserId()));
                Intent intent = new Intent(mContext, HisDetailActivity.class);
                intent.putExtra("USERID", userid);
                startActivity(intent);
                break;
            case R.id.detail_shoucang:
                if (getEatShowApp().getmUserInfo() != null) {
                    ShouCangTask scTask = new ShouCangTask(vdid, shoucangtype, "");
                    scTask.addListener(new VideoDetailTaskListener(mContext));
                    shoucangTaskId = getEatShowApp().getTaskManager().addTask(scTask);
                    shoucang.setClickable(false);
                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                    finish();
                }
                break;
            case R.id.zan:
                if (getEatShowApp().getmUserInfo() != null) {
                    ZanOrCaiTask zocTask = null;
                    zocTask = new ZanOrCaiTask(vdid, "0");
                    zocTask.addListener(new VideoDetailTaskListener(mContext));
                    zanTaskId = getEatShowApp().getTaskManager().addTask(zocTask);
                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                    finish();
                }

                break;
            case R.id.toupiao:
                if (getEatShowApp().getmUserInfo() != null) {
                    TouPiaoTask tpTask = new TouPiaoTask(userid, "");
                    tpTask.addListener(new VideoDetailTaskListener(mContext));
                    tpTaskId = getEatShowApp().getTaskManager().addTask(tpTask);

                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                    finish();
                }
                break;
            case R.id.fabiaopinglun:
                if (checkInput()) {
                    publishComment();
                    cmtContant.setText(null);
                }

                break;
            case R.id.addfocus:
                //addGuanZhu();
                if (!userinfo.isFocus()) {
                    AddOrCancleFocusTask task = new AddOrCancleFocusTask(userid, "1");
                    task.addListener(new VideoDetailTaskListener(mContext));
                    cancleFocusTaskId = getEatShowApp().getTaskManager().addTask(task);
                } else {
                    AddOrCancleFocusTask task = new AddOrCancleFocusTask(userid, "0");
                    task.addListener(new VideoDetailTaskListener(mContext));
                    addFocusTaskId = getEatShowApp().getTaskManager().addTask(task);
                }
                break;

            case R.id.back:
                if (isFull) {
                    mWebView.loadUrl("javascript:window.local_js.fullScreen();var youku=document.getElementById('youkuplayer');youku.style.width='" + webwidth + "px';youku.style.height='" + webwidth * 9 / 16 + "px';isFull = false;");
                    return;
                }
                finish();
                break;
            case R.id.more_fans_list:
                Intent moreIntent = new Intent(mContext, FansListActivity.class);
                moreIntent.putExtra("UserId", userid);
                startActivity(moreIntent);
                break;
            case R.id.fenxiang:
                if (getEatShowApp().getmUserInfo() != null) {
                    popWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                    finish();
                }
                break;
            case R.id.share_to_timeline:
                weixinsharetype = "sharefriends";
                //
                String uuid = userid;

                String vid = vdid;

                String path = youkuvid;

                String sharepath2 = "http://115.28.236.67:8096/classroom/class_video.html?userId=" + uuid + "&videoId=" + vid + "&videoPath=" + path + "";
                shareToWeiXin(sharepath2, true);
                popWindow.dismiss();
                break;
            case R.id.share_to_weixinfriend:
                weixinsharetype = "sharefriend";
                //shareToWeiXin(info.getPpnsharehtmlurl(), false);
                //String sharepath = "http://115.28.236.67:8096/classroom/class_video.html?userid=afc2d38e69ad458dbe029bdd7126e501&videoid=4c9108b8bb47407fb2a6d42c1299a9f9&videopath=XMTQ3MjE3NTIwNA";
                String uuid2 = userid;
                String vid2 = vdid;
                String path2 = youkuvid;
                String sharepath = "http://115.28.236.67:8096/classroom/class_video.html?userId=" + uuid2 + "&videoId=" + vid2 + "&videoPath=" + path2 + "";
                shareToWeiXin(sharepath, false);
                popWindow.dismiss();
                break;
            case R.id.share_to_weibo:
                //shareToWeiBo(info.getPpnsharehtmlurl());
                String uuid3 = userid;
                String vid3 = vdid;
                String path3 = youkuvid;
                String sharepath3 = "http://115.28.236.67:8096/classroom/class_video.html?userId=" + uuid3 + "&videoId=" + vid3 + "&videoPath=" + path3 + "";
                shareToWeiBo(sharepath3);
                popWindow.dismiss();
                break;
            case R.id.share_to_qq:
                String uuid5 = userid;
                String vid5 = vdid;
                String path5 = youkuvid;
                String sharepath5 = "http://115.28.236.67:8096/classroom/class_video.html?userId=" + uuid5 + "&videoId=" + vid5 + "&videoPath=" + path5 + "";
                Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
                weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);

                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, sharepath5);
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com/diyiketangImage/diyiketang_icon.png");
                // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                mTencent.shareToQQ(this, params, qqShareListener);
                popWindow.dismiss();
                break;

            case R.id.bofangliang:
                isFirst = EatShowSetting.getInstance(mContext).getIsFirstSend();
                if (isFirst) {
//                    ToastUtil.showMessage(mContent,"第一次");
                    EatShowSetting.getInstance(mContext).setIsFirstSend(false);
                    DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), getString(R.string.if_send_flour), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            doSendFlour();
                        }
                    }, null);

                } else {
//                    ToastUtil.showMessage(mContent,"不是第一次");
                    doSendFlour();
                }
                break;

        }

    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {

        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            addShareNum();

        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub

        }
    };

    @Override
    public void onResponse(BaseResponse arg0) {

        switch (arg0.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, R.string.weibosdk_toast_share_success,
                        Toast.LENGTH_LONG).show();
                //doShareWeiboGetPoint();
                //  addShareNum();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, R.string.weibosdk_toast_share_canceled,
                        Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(
                        this,
                        getString(R.string.weibosdk_toast_share_failed)
                                + "Error Message: " + arg0.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }


    }

    class VideoDetailTaskListener extends ShowToastTaskEventListener {

        public VideoDetailTaskListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
//            int resultCode = result;
//            PalLog.e("11111111111111111111",resultCode+"");

            if (taskId == videoDetailTaskId) {


                if (data != null) {

                    JSONObject d = (JSONObject) data;
//                        String rcode = d.getString("result");
//                        PalLog.e("1111111111111",rcode);

                    if (d.containsKey("data")) {
                        info = JSON.parseObject(d.getString("data"), VideoInfo.class);
                    }
                    if (d.containsKey("business")) {
                        if (!TextUtils.isEmpty(d.getString("business"))) {
                            businessInfo = JSON.parseObject(d.getString("business"), SellerInfo.class);
                        }
                    }
                }

                if (info != null) {

                    share_title = info.getVideoIntroduction();

                    zanNum = info.getZanNum();
                    //caiNum = info.getCaiNum();
                    shangNum = info.getShangNum();
                    isZan = info.getIsZan();
                    isCollect = info.getIsCollect();
                    //isCai = info.getIsCai();
                    bofangNum = info.getPlayNum();
                    zan.setText(zanNum);
                    songhuaNum = info.getShangNum();

                    bofangliang.setText(songhuaNum);
                    shoucangNum = info.getCollectNum();
                    shoucang.setText(shoucangNum);

                    fenxiangNum = info.getShareNum();
                    fenxiang.setText(fenxiangNum);
                    // cai.setText(caiNum);
                    shang.setText(shangNum);
                    videoInstrText.setText(info.getVideoIntroduction());
                    videoCreatedateText.setText(info.getCreateDate() + "上传");
                    String score = info.getScore();
                    if (ViewUtil.isNull(score) || score.equals("0")) {
                        videoScoreText.setText("--分");
                    } else {
                        videoScoreText.setText(info.getScore() + "分");
                    }
                    if (isCanSai) {
                        mToupiao.setVisibility(View.GONE);
                    } else {
                        toupiaoNum = info.getVoteNum();
                        mToupiao.setText(toupiaoNum);
                    }
                    if (!isCollect) {
                        shoucangtype = "1";
                        shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_checked, 0, 0);
                    } else {
                        shoucangtype = "0";
                        shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_unchecked, 0, 0);
                    }
                    if (!isZan) {
                        zan.setClickable(false);
                        zan.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.zan_checked, 0, 0);
                    } else {
                        zan.setClickable(true);
                        zan.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.zan_unchecked, 0, 0);
                    }

                    youkuvid = info.getPath();
                    if (youkuvid != null) {
                        goPlay();
                    }
                }

                if (businessInfo != null && businessInfo.getBusinessId() != null) {
                    sellerLayout.setVisibility(View.VISIBLE);
                    ImageCache.getInstance(mContext).loadBitmapToView(sellerlogo, businessInfo.getBusinessLogo(), new ViewUtil.Size(ViewUtil.dip2px(mContext, 90), ViewUtil.dip2px(mContext, 70)));
                    sellerName.setText(businessInfo.getBusinessName());
                    sellerType.setText(businessInfo.getBusinessType());
                    sellerRenjun.setText("人均￥" + businessInfo.getAverageSpend());
                    try {
                        rating.setRating(Float.parseFloat(businessInfo.getBusinessScore()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    sellerLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String fdid = businessInfo.getBusinessId();
                            Intent intent = new Intent(mContext, SellerDetailActivity.class);
                            intent.putExtra("BSUINESSID", fdid);
                            startActivity(intent);
                        }
                    });
                } else {
                    sellerLayout.setVisibility(View.GONE);
                }

//                if(isCai){
//                    cai.setCompoundDrawablesWithIntrinsicBounds(R.drawable.cai_btn_checked,0,0,0);
//                }else{
//                    cai.setCompoundDrawablesWithIntrinsicBounds(R.drawable.cai_btn_unchecked,0,0,0);
//                }
                //getUserInfo();

                if (getEatShowApp().getmUserInfo() != null) {
                    getAnchorFansList();
                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    startActivity(lintent);
                    finish();
                }

            } else if (taskId == zanTaskId) {
                if (info == null) return;
                info.setIsZan(false);
                try {
                    info.setZanNum(String.valueOf((Integer.valueOf(zanNum) + 1)));

                } catch (Exception e) {
                    e.printStackTrace();
                }

                zan.setText(info.getZanNum());
                zan.setClickable(false);
                zan.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.zan_checked, 0, 0);
            } else if (taskId == shareNumTaskId) {
                if (info == null) return;
                try {
                    info.setShareNum(String.valueOf((Integer.valueOf(info.getShareNum()) + 1)));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                fenxiang.setText(info.getShareNum());
            } else if (taskId == tpTaskId) {
                if (info == null) return;
                try {
                    info.setVoteNum(String.valueOf((Integer.valueOf(info.getVoteNum()) + 1)));

                } catch (Exception e) {
                    e.printStackTrace();
                }
                mToupiao.setText(info.getVoteNum());
                ToastUtil.showMessage(mContent, "投票成功");
            } else if (taskId == shoucangTaskId) {
                if (info == null) return;
                if (!info.getIsCollect()) {
                    info.setIsCollect(true);
                    shoucangtype = "0";
                    info.setCollectNum(String.valueOf((Integer.valueOf(info.getCollectNum()) - 1)));
                    shoucang.setText(info.getCollectNum());

                    shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_unchecked, 0, 0);
//                    shoucang.setClickable(false);
                    // updateView();

                } else {
                    info.setIsCollect(false);
                    shoucangtype = "1";
                    info.setCollectNum(String.valueOf((Integer.valueOf(info.getCollectNum()) + 1)));
                    shoucang.setText(info.getCollectNum());

                    shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_checked, 0, 0);
//                    shoucang.setClickable(false);
                    //updateView();
                }
                shoucang.setClickable(true);

            }
//            else if(taskId ==caiTaskId){
//                info.setIsCai(false);
//                info.setCaiNum(String.valueOf((Integer.valueOf(caiNum) + 1)));
//            }else if(taskId ==cancleCaiId){
//                info.setIsCai(true);
//                info.setCaiNum(String.valueOf((Integer.valueOf(caiNum) - 1)));
//            }
            else if (taskId == getUserInfoTaskId) {
                userinfo = (EatShowUserInfo) data;
                if (userinfo != null) {
                    ImageCache.getInstance(mContext).loadBitmapToView(
                            userLogo,
                            userinfo.getUserLogo(),
                            new ViewUtil.Size(ViewUtil.dip2px(mContext, 60), ViewUtil.dip2px(
                                    mContext, 60)));
//                    if(userinfo.isGame()){
//                        shoucang.setVisibility(View.VISIBLE);
//                    }
//                    nickText.setText(userinfo.getNickName());
//                    signText.setText(userinfo.getUserSign());
                    if (userinfo.getNickName() != null) {
                        try {
                            nickText.setText(URLDecoder.decode(userinfo.getNickName(), "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    if (userinfo.getUserSign() != null) {
                        try {
                            signText.setText(URLDecoder.decode(userinfo.getUserSign(), "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    if (!userinfo.isFocus()) {
                        //focusImge.setText("取消关注");
                        addFocusImg.setImageResource(R.drawable.yiguanzhu);
                        userinfo.setIsFocus(false);
                    } else {
                        //focusImge.setText("关注");
                        addFocusImg.setImageResource(R.drawable.weiguanzhu);
                        userinfo.setIsFocus(true);
                    }

                    if (0 != userinfo.isVip()) ;


                    //getAnchorFansList();
                    getVideoDetail();
                }
            } else if (taskId == fanListTaskId) {
                if (data != null) {
                    List<EatShowUserInfo> list = (List<EatShowUserInfo>) data;
                    if (list != null && list.size() > 0) {
                        dtfansAdapter.clearData();
                        dtfansAdapter.updateData(list);
                        fansListDivider.setVisibility(View.VISIBLE);
                    } else {
                        mFansLayout.setVisibility(View.GONE);
                        fansListDivider.setVisibility(View.GONE);
                    }
//                    getCommentList();
                }
            } else if (taskId == commentListTaskId) {
                if (data != null) {
                    List<CommentInfo> list = (List<CommentInfo>) data;
                    if (currentPage == 1) {
                        cmtAdapter.clearData();
                    }
                    if (list != null && list.size() > 0) {
                        cmtAdapter.updateData(list);
                    }
                    currentPage = result;
                }
            } else if (taskId == publishCmtTaskId) {
                Toast.makeText(mContext, R.string.pinglun_success, Toast.LENGTH_SHORT)
                        .show();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(cmtContant.getWindowToken(), 0);
                cmtContant.setText("");
                currentPage = 1;
                getCommentList();
            } else if (taskId == addFocusTaskId) {
                if (userinfo == null) return;
//                if(info.getIsFocus()){
//                    //focusImge.setText("取消关注");
                addFocusImg.setImageResource(R.drawable.yiguanzhu);
                userinfo.setIsFocus(false);
//                }
//                else{
//                    //focusImge.setText("关注");
//                    addFocusImg.setImageResource(R.drawable.focus_checked);
//                    info.setIsFocus(true);
//                }
            } else if (taskId == cancleFocusTaskId) {
                if (userinfo == null) return;
                addFocusImg.setImageResource(R.drawable.weiguanzhu);
                userinfo.setIsFocus(true);
            } else if (taskId == sendflourTaskId) {
                if (info == null) return;
                try {
                    info.setShangNum(String.valueOf((Integer.valueOf(info.getShangNum()) + 1)));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                bofangliang.setText(info.getShangNum());
                ToastUtil.showMessage(mContent, "送花成功！");
//                JSONObject js = (JSONObject) data;
//                String msg = js.getString("message");
//                ToastUtil.showMessage(mContent,msg);
            }

        }


        private void updateView() {
            shoucang.setClickable(true);
            if (info.getIsCollect()) {
                shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_unchecked, 0, 0);

            } else {
                shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_checked, 0, 0);
            }

        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == videoDetailTaskId) {

                int noCode = errorCode;
                PalLog.e("fanhuide", errorCode + "");
                if (noCode == 8001032) {
                    DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), getString(R.string.no_quanxian), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent gmIntent = new Intent(mContext, GouMaiKeChengActivity.class);
                            gmIntent.putExtra("ZUOZHE", teacherString);
                            gmIntent.putExtra("FEE", feeString);
                            gmIntent.putExtra("TITLE", titleString);
                            gmIntent.putExtra("videoid", vdid);
                            mContext.startActivity(gmIntent);
//                            finish();
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
//                            finish();
                        }
                    });
                }
//                else if (noCode == 8001031){
//                    DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), getString(R.string.no_vip), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            Intent gmIntent = new Intent(mContext, OpenVipActivity.class);
////                            gmIntent.putExtra("ZUOZHE", teacherString);
////                            gmIntent.putExtra("FEE", feeString);
////                            gmIntent.putExtra("TITLE", titleString);
////                            gmIntent.putExtra("videoid", vdid);
//                            mContext.startActivity(gmIntent);
//                            finish();
//                        }
//                    }, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            finish();
//                        }
//                    });
//                }
                //getVideoDetail();
                getAnchorFansList();
            } else if (taskId == getUserInfoTaskId) {
                // getUserInfo();
                getVideoDetail();
            } else if (taskId == fanListTaskId) {
                // getAnchorFansList();
            }
        }
    }


    //fenxiang

    class WeixinShareReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            System.out.println(intent.getAction());
            weixinuseropenid = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);


            if (intent.getAction().equalsIgnoreCase(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION)) {
                addShareNum();
            } else if (intent.getAction().equalsIgnoreCase(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION)) {

            }
            if (mWeixinShareReceive != null) {
                unregisterReceiver(mWeixinShareReceive);
                mWeixinShareReceive = null;
            }
        }

    }

    private void shareToWeiXin(String shareUrl, boolean isTimeLine) {
        if (!api.isWXAppSupportAPI() || !api.isWXAppInstalled()) {
            Toast.makeText(mContext, R.string.need_weixin_app, Toast.LENGTH_SHORT).show();
            return;
        }
        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        //msg.title = ppntitle;
        if (isTimeLine) {
            msg.title = share_title;
        } else {
            msg.title = "第一课堂";
        }
        msg.description = share_title;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
        weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);
        if (weixinshareByte != null && weixinshareByte.length != 0) {
            msg.thumbData = weixinshareByte;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }


    private void shareToWeiBo(String webpage) {
        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
//		if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
//        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        // if (hasText) {
        // weiboMessage.mediaObject = getTextObj();
        // }
        // if (hasImage) {
        // weiboMessage.mediaObject = getImageObj();
        // }
//        if (!TextUtils.isEmpty(webpage)) {
//            TextObject textobject = new TextObject();
//            textobject.text = "第一课堂";
//            weiboMessage.textObject = textobject;
//            WebpageObject mediaObject = new WebpageObject();
//            mediaObject.identify = Utility.generateGUID();
//            mediaObject.defaultText = "第一课堂";
//            mediaObject.title = "第一课堂";
//            mediaObject.description = share_title;
//            mediaObject.actionUrl = webpage;
//            if (weiboShareBitmap != null) {
//                mediaObject.setThumbImage(weiboShareBitmap);
//            } else {
//                mediaObject.setThumbImage(BitmapFactory.decodeResource(
//                        getResources(), R.drawable.app_icon));
//            }
//            weiboMessage.mediaObject = mediaObject;
//        }
        // if (hasMusic) {
        // weiboMessage.mediaObject = getMusicObj();
        // }
        // if (hasVideo) {
        // weiboMessage.mediaObject = getVideoObj();
        // }
            /*
             * if (hasVoice) { weiboMessage.mediaObject = getVoiceObj(); }
			 */

        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
//        request.multiMessage = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        AuthInfo authInfo = new AuthInfo(this, ProtocolConst.WEIBO_APP_KEY, ProtocolConst.WEIBO_REDIRECT_URL, ProtocolConst.WEIBO_SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
        String token = "";
        if (accessToken != null) {
            token = accessToken.getToken();
            weibouserid = accessToken.getUid();
        }
//        mWeiboShareAPI.sendRequest(this, request, authInfo, token, new WeiboAuthListener() {
//
//
//            @Override
//            public void onWeiboException(WeiboException arg0) {
//            }
//
//            @Override
//            public void onComplete(Bundle bundle) {
//                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
//                AccessTokenKeeper.writeAccessToken(getApplicationContext(), newToken);
//                weibouserid = newToken.getUid();
////                    Toast.makeText(getApplicationContext(), "UID = "+weiboOpenId+"onAuthorizeComplete token = " + newToken.getToken(), 0).show();
//            }
//
//            @Override
//            public void onCancel() {
//            }
//        });


    }

    private boolean checkInput() {
        cmtText = cmtContant.getText().toString().trim();

        if (TextUtils.isEmpty(cmtText)) {
            Toast.makeText(mContext, R.string.no_cmt, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

    private void showshujuDialog() {
        DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), getString(R.string.useshuju), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                youkuPlayer.playVideo(youkuvid);
            }
        }, null);
    }

    private class JsObject {
        @JavascriptInterface
        public void fullScreen() {
            fullscreen();
        }
    }

    public String getTagByUrl(String url) {
        if (url.contains("qq")) {
            return "tvp_fullscreen_button"; // http://m.v.qq.com
        } else if (url.contains("youku")) {
            return "x-zoomin";              // http://www.youku.com
        } else if (url.contains("bilibili")) {
            return "icon-widescreen";       // http://www.bilibili.com/mobile/index.html
        } else if (url.contains("acfun")) {
            return "controller-btn-fullscreen"; //http://m.acfun.tv   无效
        } else if (url.contains("le")) {
            return "hv_ico_screen";         // http://m.le.com  无效
        } else if (url.contains("yk")) {
            return "x-zoomin";
        }
        return "";
    }

    private boolean isFull = false;

    private void fullscreen() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    webLayout.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    mWebView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
                }
            });
            isFull = true;
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    int width = ViewUtil.getScreenWidth(mContext);
                    int height = width * 9 / 16;
                    webLayout.setLayoutParams(new RelativeLayout.LayoutParams(width, height));
                    mWebView.setLayoutParams(new LinearLayout.LayoutParams(width, height));
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                }
            });
            isFull = false;

        }
    }


}
